<template>
  <div class="password-strength">
    <div class="password-strength-bar" :class="`password-strength-level-${level}`"></div>
  </div>
</template>

<script setup>
  import { ref, onMounted, watch } from 'vue';

  const props = defineProps({
    modelValue: {
      type: String,
      default: '',
    },
  });

  const level = ref(0);

  const strength = (val) => {
    let newLevel = 0;
    // 长度
    const hasLength = val.length >= 6;
    // 包含数字
    const hasNumber = /\d/.test(val);
    // 包含小写英文
    const hasLovercase = /[a-z]/.test(val);
    // 包含大写英文
    const hasUppercase = /[A-Z]/.test(val);
    // 没有连续的字符3位
    const noContinuity = !/(\w)\1{2}/.test(val);
    // 包含特殊字符
    const hasSpecial = /[`~!@#$%^&*()_+<>?:"{},./;'[\]]/.test(val);

    if (val.length <= 0) {
      newLevel = 0;
      level.value = newLevel;
    } else if (!hasLength) {
      newLevel = 1;
      level.value = newLevel;
    } else {
      if (hasNumber) {
        newLevel += 1;
      }
      if (hasLovercase) {
        newLevel += 1;
      }
      if (hasUppercase) {
        newLevel += 1;
      }
      if (noContinuity) {
        newLevel += 1;
      }
      if (hasSpecial) {
        newLevel += 1;
      }
      level.value = newLevel;
    }
  };

  watch(
  () => props.modelValue,
  (val) => {
      strength(val);
    }
  );

  onMounted(async () => {
    strength(props.modelValue);
  });
</script>

<style lang="less" scoped>
  .password-strength {
    height: 5px;
    width: 100%;
    background: var(--color-text-4);
    border-radius: 5px;
    position: relative;
    margin: 10px 0;
  }
  .password-strength:before {
    left: 20%;
  }
  .password-strength:after {
    right: 20%;
  }
  .password-strength:before, .password-strength:after {
    position: absolute;
    content: "";
    display: block;
    width: 20%;
    height: inherit;
    border: 5px solid var(--color-bg-white);
    border-top: 0;
    border-bottom: 0;
    z-index: 1;
    background-color: transparent;
    box-sizing: border-box;
  }
  .password-strength-bar {
    position: absolute;
    height: inherit;
    width: 0;
    border-radius: inherit;
    transition: width .5s ease-in-out, background .25s;
    background: transparent;
  }
  .password-strength-level-1 {
    width: 20%;
    background-color: var(--color-danger-light-4);
  }
  .password-strength-level-2 {
    width: 40%;
    background-color: var(--color-danger-light-4);
  }
  .password-strength-level-3 {
    width: 60%;
    background-color: var(--color-warning-light-4);
  }
  .password-strength-level-4 {
    width: 80%;
    background-color: var(--color-success-light-4);
  }
  .password-strength-level-5 {
    width: 100%;
    background-color: var(--color-success-light-4);
  }
</style>
